<template>
  <div class="ai-chat-container">
    <div class="ai-chat-header">
      <h2>AI问答</h2>
    </div>

    <div class="chat-messages" ref="chatMessages">
      <ChatBubble v-for="(msg, index) in messages"
                  :key="index"
                  :message="msg"
                  :show-play="false"
      >
      </ChatBubble>
    </div>

    <div class="chat-input-container">
      <textarea
          class="chat-input"
          v-model="newMessage"
          @keydown.enter.prevent="handleEnterKey"
          placeholder="输入提问内容，AI智能回答(Shift+Enter换行，Enter发送)"
          ref="chatTextarea"
          rows="2"
      ></textarea>
      <button class="send-button" @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick, watch, defineProps, defineEmits } from 'vue';
import ChatBubble from "@/components/common/ChatBubble.vue";
import {ElMessage} from "element-plus";
import {getResumeRevisionSuggestions} from "@/http/m_api/template";

const props = defineProps({
  resumeId: {
    type: String,
    required: true
  },
});

const emit = defineEmits(['message-sent', 'message-received', 'api-response', 'api-error', 'resume-validation-error']);

const messageId = ref(0);
const isLoading = ref(false);
const showWarning = ref(false);

const defalutOpening = {
  id: 0,
  type: true, // true为AI，false为用户
  content: `欢迎使用AI助手，有什么可以帮助您的吗？`
}

const messages = ref([defalutOpening]);


const newMessage = ref('');
const chatMessages = ref(null);
const chatTextarea = ref(null);

// 验证简历数据是否为空
const validateResumeData = () => {
  // 检查简历数据是否存在且不为空
  if (props.resumeId === undefined || props.resumeId === ''){
    return false;
  }
  return true;
};

// 发送消息到后端的函数
const sendToBackend = async (userMessage) => {
  try {
    isLoading.value = true;

    const requestData = {
      // userId:
      resumeId: props.resumeId,
      userPrompt: userMessage,
      minLength: 100,
      maxLength: 300
    };

    const response = await getResumeRevisionSuggestions(requestData)

    const result = await response.data;


    return result.advice;
  } catch (error) {
  } finally {
    isLoading.value = false;
  }
};

const sendMessage = async () => {
  if (newMessage.value.trim() === '') {
    return;
  }

  // 验证简历数据
  if (!validateResumeData()) {
    ElMessage.warning('您还没有选中要修改的简历模块，请选择模块后再进行咨询！')
    return; // 阻止发送请求
  }

  // 添加用户消息
  const userMessageText = newMessage.value.replace(/\n/g, '<br>');
  const userMessage = {
    id: getMessageId(),
    type: false,
    content: userMessageText,
    timestamp: new Date().toISOString()
  };

  messages.value.push(userMessage);
  emit('message-sent', userMessage);

  // 保存原始消息内容
  const userMessageContent = newMessage.value;
  newMessage.value = '';

  // 添加加载状态消息
  const loadingMessage = {
    id: getMessageId(),
    type: true,
    content: '正在分析中...',
    isLoading: true
  };
  messages.value.push(loadingMessage);

  try {
    // 发送到后端
    const backendResponse = await sendToBackend(userMessageContent);

    // 移除加载消息
    messages.value = messages.value.filter(msg => !msg.isLoading);

    // 处理后端响应
    let aiResponse;
    if (backendResponse) {
      aiResponse = backendResponse;
    } else {
      // 如果后端没有返回有效响应，使用默认回复
      aiResponse = getDefaultAIResponse(userMessageContent);
    }

    const aiMessage = {
      id: getMessageId(),
      type: true,
      content: aiResponse,
      timestamp: new Date().toISOString(),
      backendData: backendResponse // 保存完整的后端响应数据
    };

    messages.value.push(aiMessage);
    emit('message-received', aiMessage);

  } catch (error) {
    // 移除加载消息
    messages.value = messages.value.filter(msg => !msg.isLoading);

    // 添加错误消息
    const errorMessage = {
      id: getMessageId(),
      type: true,
      content: '抱歉，服务暂时不可用，请稍后再试。',
      isError: true,
      timestamp: new Date().toISOString()
    };

    messages.value.push(errorMessage);
    emit('message-received', errorMessage);
  }

  // 滚动到底部
  scrollToBottom();
};

const handleEnterKey = (event) => {
  if (event.shiftKey) {
    // 如果按下Shift+Enter，则插入换行符
    const start = event.target.selectionStart;
    const end = event.target.selectionEnd;
    newMessage.value = newMessage.value.substring(0, start) + '\n' + newMessage.value.substring(end);

    // 在下一个事件循环中设置光标位置
    nextTick(() => {
      event.target.selectionStart = event.target.selectionEnd = start + 1;
    });
  } else {
    // 如果只按下Enter，则发送消息
    event.preventDefault();
    sendMessage();
  }
};

const getDefaultAIResponse = (message) => {
  // 默认的AI回复逻辑（作为后备方案）
  if (message.includes('你好') || message.includes('嗨') || message.includes('hi') || message.includes('hello')) {
    return '你好！我是AI助手，有什么可以帮助您的吗？';
  } else if (message.includes('简历') || message.includes('求职')) {
    return '关于简历，我建议您突出自己的专业技能和项目经验，使用具体的数据和成果来展示您的能力。您需要针对不同的职位定制简历内容，确保与职位描述相匹配。';
  } else if (message.includes('技能') || message.includes('能力')) {
    return '在简历中展示技能时，建议分类列出，如技术技能、软技能、语言能力等。对于关键技能，可以添加熟练程度的说明，并在工作经历中展示如何应用这些技能解决实际问题。';
  } else if (message.includes('项目') || message.includes('经验')) {
    return '描述项目经验时，建议使用STAR法则：情境(Situation)、任务(Task)、行动(Action)和结果(Result)。清晰说明您的角色、责任和贡献，以及项目成果和影响。量化成果会让您的简历更有说服力。';
  } else {
    return '感谢您的提问。如果您有关于简历、求职或职业发展的问题，我很乐意为您提供建议和指导。请告诉我您需要什么样的帮助？';
  }
};

const getMessageId = () => {
  return messageId.value++;
};

const scrollToBottom = async () => {
  await nextTick();
  if (chatMessages.value) {
    chatMessages.value.scrollTop = chatMessages.value.scrollHeight;
  }
};

// 手动关闭警告
const closeWarning = () => {
  showWarning.value = false;
};

// 重试发送消息的函数
const retryMessage = async (messageContent) => {
  newMessage.value = messageContent;
  await sendMessage();
};

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  scrollToBottom();
}, { deep: true });

// 监听简历数据变化
watch(
    () => props.resumeId,
    (newVal, oldVal) => {
      if (newVal && Object.keys(newVal).length > 0) {
        // 如果之前显示警告，现在有数据了就隐藏警告
        if (showWarning.value) {
          showWarning.value = false;
        }
      }
      messages.value = [defalutOpening]
      messageId.value = 1;
    },
    { deep: true }
);

onMounted(() => {
  scrollToBottom();
});
</script>

<style lang="scss" scoped>
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 400px;
  background-color: #f8f8f5;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.ai-chat-header {
  background-color: #f8f8f5;
  padding: 15px;
  text-align: center;
  border-bottom: 1px solid #e0e0e0;
}

.ai-chat-header h2 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: bold;
}

.chat-messages {
  flex: 1;
  padding-left: 0;
  padding-right: 0;
  padding-top: 10px;
  max-height: 60vh;
  overflow-y: auto;
  background-color: #f8f8f5;
}

.message {
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
}

.message.ai {
  justify-content: flex-start;
}

.message.user {
  justify-content: flex-end;
}

.message-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  margin: 5px 10px;
}

.message.ai .message-avatar {
  background-color: #333;
  color: white;
}

.message.user .message-avatar {
  background-color: #4cd964;
  color: white;
}

.message-content {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 10px;
  word-break: break-word;
}

.message-content.ai {
  background-color: #444;
  color: white;
}

.message-content.user {
  background-color: #4cd964;
  color: white;
}

.message-content p {
  margin: 0;
}

.chat-input-container {
  display: flex;
  padding: 15px;
  background-color: white;
  border-top: 1px solid #e0e0e0;
  align-items: flex-start;
}

.chat-input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
  resize: none;
  margin-top: auto;
  height: 150px;
  max-height: 150px;
  font-family: inherit;
  font-size: inherit;
  line-height: 1.5;
  overflow-y: auto;
}

.send-button {
  background-color: #f7b731;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  margin-left: 10px;
  cursor: pointer;
  transition: background-color 0.3s;
  height: 40px;
}

.send-button:hover {
  background-color: #e5a82e;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .message-content {
    max-width: 85%;
  }
}
</style>